package com.eat.fish_service.filter;

import com.eat.common_utils.JwtUtils;
import com.eat.common_utils.R;
import com.eat.common_utils.ResponseUtil;
import com.eat.common_utils.ResultCode;
import com.eat.fish_service.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author CZF
 * @create 2022-09-05 4:49
 */

@WebFilter(filterName = "headerAutoLoginFilter", urlPatterns = "/web/user/login")
@Slf4j
public class HeaderAutoLoginFilter implements Filter {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserService userService;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        Cookie[] cookies = req.getCookies();
        String token = req.getHeader("token"); //从header中获取存token的cookie对象
        if (StringUtils.isEmpty(token)) { //如果token是空
            chain.doFilter(request, response); //过滤放行到账号密码登录接口
        } else {

            boolean isValid=false;
            try {
                isValid = JwtUtils.checkTokenByToken(token, redisTemplate);
            } catch (Exception e) {  //jwt解析不了字符串会报错，于是就直接返回给响应说token失效
                log.error("jwt验证异常，token字符串格式错误:"+e.toString());
                ResponseUtil.out(req,res, R.error().code(ResultCode.TOKEN_INVALID).message("token失效，请跳转到登录页面重新登录"));
            }

            if (isValid) {  //看token是否有效
                String username = JwtUtils.getUsername(token);
                R r = userService.getUserMess(username, req, res); //获取用户信息
                ResponseUtil.out(req,res, r);//使用ResponseUtil工具类返回响应
            } else { //token无效，返回给前端告诉他token无效了，删除localstorage的token，请求头不携带token
                ResponseUtil.out(req,res, R.error().code(ResultCode.TOKEN_INVALID).message("token失效，请跳转到登录页面重新登录"));//使用ResponseUtil工具类返回响应
            }
        }
    }
}
